class ContentRecorded extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            customTypeList: '',
            typeCode: '',
            img: '/pic/upload_ioc.png',
            inputValue: {},
            customTypeCode: ''
        };
    }

    initComplete(nodeInfo, resource) {
        this.layer = layui.layer;
        // noinspection ES6ModulesDependencies
        this.form = layui.form();
        let isUrl1 = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
        let isUrl2 = /^(native:)/;
        //自定义验证规则
        this.form.verify({
            title: function (value) {
                if (value.length < 2) {
                    return '标题至少得2个字符!';
                }
            },
            description: function (value) {
                if (value.length < 2) {
                    return '描述至少得2个字符!';
                }
            },
            content_url: function (value) {
                if (value.length !== 0 && !(isUrl1.test(value) || isUrl2.test(value))) {
                    return '内容地址不是正确的Url！';
                }
            }
        });

        this.form.on('submit(submit)', () => {
            postJson("/cms/appResource/saveResource.x", $('#form').serialize(), () => {
                parent.layer.msg('录制成功，请等待审核。', {icon: 6});
                this.cleanForm();
            });
            return false;
        });

        layui.upload({
            url: '/cms/appResource/uploadFile.x?isTemp=' + true
            , success: function (res) {
                this.setState({
                    iconUrl: res.data.imagePath,
                    img: res.data.imageUrl
                });
            }.bind(this)
        });

        this.form.on('select(customType)', () => {
            this.setState({}, () => {
                this.form.render();
            });
        });

        this.cleanForm(() => {
            const customTypeList = nodeInfo.customTypeList;
            let inputVolue = {};
            console.log("resource: ", resource);
            if (resource) {
                this.state.customTypeCode = '';
                this.state.img = resource.icon_url;
                inputVolue['title'] = resource.title;
                inputVolue['content_url'] = resource.content_url;
                inputVolue['description'] = resource.description;
                inputVolue['resource_id'] = resource.resource_id;
                const resourceCustomContents = JSON.parse(resource.customContent ? resource.customContent : '[]');
                for (const i in customTypeList) {
                    const customType = customTypeList[i];
                    const customContents = JSON.parse(customType.custom_content ? customType.custom_content : '[]');
                    for (const j in customContents) {
                        const customKey = customContents[j].customKey;
                        for (const k in resourceCustomContents) {
                            if (customKey === resourceCustomContents[k].customKey) {
                                this.state.customTypeCode = customType.custom_type_code;
                                inputVolue[customKey] = resourceCustomContents[k].customValue;
                                break;
                            }
                        }
                    }
                }
            }
            this.setState({
                customTypeList: customTypeList,
                typeCode: nodeInfo.resourceType.type_code,
                inputValue: inputVolue
            }, function () {
                this.setState({
                    customPerms: ''
                }, function () {
                    this.form.render();
                });
            }.bind(this));
            this.refs.ueditorList.layuiInitComplete();
        });
    }

    cleanForm(callback) {
        this.setState({
            inputValue: {},
            iconUrl: '',
            img: '/pic/upload_ioc.png'
        }, () => {
            if (callback) {
                callback();
            }
        });
    }

    spinnerView(spinnerMap, volue) {
        let newArry = [];
        if (spinnerMap) {
            for (let key in spinnerMap) {
                if (volue === key) {
                    newArry.push(<option value={key} selected={true}>{spinnerMap[key]}</option>)
                } else {
                    newArry.push(<option value={key}>{spinnerMap[key]}</option>)
                }
            }
        } else {
            newArry.push(<option value="-1">无</option>)
        }
        return newArry;
    }

    selectUeditor() {
        layer.open({
            type: 1,
            shade: false,
            area: ['60%', 'auto'],
            title: '自定义内容',
            maxHeight: '80%',
            shadeClose: true,
            maxmin: true,
            content: $('#select_ueditor') //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        });
    }

    selectCallback(id) {
        let curWwwPath = window.document.location.href;
        //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
        let pathName = window.document.location.pathname;
        let pos = curWwwPath.indexOf(pathName);
        //获取主机地址，如： http://localhost:8083
        let localhostPaht = curWwwPath.substring(0, pos);
        this.refs.content_url.value = localhostPaht + "/api/v3/cms/anon/getContent?ueditorId=" + id;
        layer.closeAll();
    }

    customAddPerms() {
        if (this.state.customTypeList) {
            return this.state.customTypeList.map(function (array) {
                let customTypeCode = this.refs.customType.value;
                if (customTypeCode === array.custom_type_code && array.customContents) {
                    return array.customContents.map(function (customContent) {
                        const volue = this.state.inputValue[customContent.customKey] ? this.state.inputValue[customContent.customKey] : '';
                        if (customContent.customType === 'CMS_CUSTOM_SORT') {
                            return (<div className="layui-form-item">
                                <label className="layui-form-label">{customContent.customName}</label>
                                <div className="layui-input-inline">
                                    <select name="customValues">
                                        {this.spinnerView(customContent.spinnerMap, volue)}
                                    </select>
                                    <input type="hidden" name="customKeys" value={customContent.customKey}/>
                                    <input type="hidden" id="sortCustomDescribes"
                                           name="sortCustomDescribes"
                                           value={customContent.customDescribe ? customContent.customDescribe : ''}/>
                                </div>
                            </div>);
                        } else {
                            return (<div className="layui-form-item">
                                    <label className="layui-form-label">{customContent.customName}</label>
                                    <div className="layui-input-block">
                                        <input type="hidden" id="customKeys" name="customKeys"
                                               value={customContent.customKey}/>
                                        <input type="hidden" id="customDescribes"
                                               name="customDescribes"
                                               value={customContent.customDescribe ? customContent.customDescribe : ''}/>
                                        <input id="customValues" name="customValues" data-verify="customValues"
                                               value={volue}
                                               onChange={(e) => this.inputOnChange(e, customContent.customKey)}
                                               placeholder={"请输入" + customContent.customName}
                                               autoComplete="off" className="layui-input" type="text"/>
                                    </div>

                                </div>
                            )
                        }
                    }.bind(this))
                }
            }.bind(this))
        }
    }

    inputOnChange(e, index) {
        this.state.inputValue[index] = e.target.value;
        this.setState({});
    }

    render() {
        return <form id="form" className="layui-form layui-form-pane">
            <input type="hidden" name="resource_id"
                   value={this.state.inputValue['resource_id'] ? this.state.inputValue['resource_id'] : ''}/>
            <input type="hidden" name="type_code" value={this.state.typeCode}/>
            <div className="layui-form-item">
                <label className="layui-form-label">资源类型</label>
                <div className="layui-input-inline">
                    <select name="customType" ref="customType" data-filter="customType">
                        {
                            this.state.customTypeList ? this.state.customTypeList.map(function (array) {
                                if (this.state.customTypeCode === array.custom_type_code) {
                                    return (<option
                                        value={array.custom_type_code} selected={true}>{array.custom_type_name}
                                    </option>);
                                } else {
                                    return (<option
                                        value={array.custom_type_code}>{array.custom_type_name}
                                    </option>);
                                }
                            }.bind(this)) : <option value="default" selected="selected">默认</option>
                        }
                    </select>
                </div>
            </div>

            <div className="layui-form-item">
                <label className="layui-form-label">标题</label>
                <div className="layui-input-block">
                    <input name="title" ref="title" data-verify="title" placeholder="请输入资源标题"
                           autoComplete="off" className="layui-input" type="text"
                           value={this.state.inputValue['title'] ? this.state.inputValue['title'] : ''}
                           onChange={(e) => this.inputOnChange(e, 'title')}/>
                </div>
            </div>

            <div className="layui-form-item">
                <label className="layui-form-label">描述</label>
                <div className="layui-input-block">
                    <input name="description" ref="description" data-verify="description" placeholder="请输入资源描述"
                           autoComplete="off" className="layui-input" type="text"
                           value={this.state.inputValue['description'] ? this.state.inputValue['description'] : ''}
                           onChange={(e) => this.inputOnChange(e, 'description')}/>
                </div>
            </div>

            <div className="layui-form-item">
                <label className="layui-form-label">内容地址</label>
                <div className="layui-input-block">
                    <input name="content_url" ref="content_url" data-verify="content_url" placeholder="请输入内容地址"
                           autoComplete="off" className="layui-input" type="text"
                           style={{maxWidth: '80%', float: 'left', marginRight: '10px'}}
                           value={this.state.inputValue['content_url'] ? this.state.inputValue['content_url'] : ''}
                           onChange={(e) => this.inputOnChange(e, 'content_url')}/>
                    <button className="layui-btn" type="button" onClick={() => this.selectUeditor()}>自定义内容</button>
                </div>
            </div>

            {this.customAddPerms()}

            <div className="layui-form-item">
                <label className="layui-form-label">资源图标</label>
                <div className="layui-input-block"
                     style={{'background': '#FFFFFF', 'padding': '20px', 'border': '1px solid #e6e6e6'}}>

                    <div style={divItemStyle}>
                        <div className="Center-Container" style={divImgStyle}>
                            <img className="Absolute-Center" ref="img" style={imgStyle}
                                 onClick={() => this.props.showImage(this.state.img)} src={this.state.img}/>
                        </div>
                        <hr/>
                        <div style={{'text-align': 'center', margin: '0 auto'}}>
                            <input type="hidden" ref="icon_url" name="icon_url" value={this.state.iconUrl}
                                   data-verify="icon_url"/>
                            <input type="file" name="file" className="layui-upload-file" data-title="选择一张图片"/>
                        </div>
                    </div>

                    <div style={{font: '0px/0px sans-serif', clear: 'both', display: 'block'}}/>
                </div>
            </div>

            <div className="layui-form-item">
                <button id="savebt" className="layui-btn layui-btn-primary" type="button"
                        onClick={() => this.cleanForm()}>
                    清空数据
                </button>
                <button id="savebt" className="layui-btn layui-btn-normal" data-submit=""
                        data-filter="submit">
                    新增保存
                </button>
            </div>

            <div id="select_ueditor"
                 style={{display: 'none', paddingLeft: '10px', paddingRight: '10px', paddingTop: '20px'}}>
                <UeditorList ref="ueditorList" selectCallback={(id) => this.selectCallback(id)}/>
            </div>

        </form>
    }
}

let divItemStyle = {
    border: '1px solid #CDCDC1',
    float: 'left',
    padding: '5px',
    width: '200px',
    height: '165px',
    marginLeft: '10px'
};

let divImgStyle = {
    width: '100%',
    height: '100px'
};

let imgStyle = {
    'max-height': '100%',
    'max-width': '100%'
};